<?php
class UaModel extends UaObject
{
	var $primaryKey = "id";
	var $id = null;
	var $type_status = array("0"=>"否","1"=>"是");
	var $table;

	function setPrimaryKey($p = null)
	{
		if (is_null($p)) {
			$p = "id";
		}
		$this->primaryKey = $p;
	}

	function getPrimaryKey()
	{
		return $this->primaryKey;
	}

	function setId($id)
	{
		$this->id = $id;
	}

	function getId()
	{
		return $this->id;
	}

	/**
	 * 代替旧版本1.0的delete
	 * @param Mixed $id_array 要删除的唯一ID，数组或者整数
	 * @return Boolean
	 */
	function del($id_array, $conditions = null)
	{
		global $g_db;
		$del_id = $this->primaryKey;
		$tmp_ids = null;
		if (is_array($id_array))
		{
			$tmp_ids = implode(",",$id_array);
			$cond[] = "$del_id in (".$tmp_ids.")";
		}
		else
		{
			$cond[] = "$del_id=".intval($id_array);
		}
		if(isset($conditions)) {
			if(is_array($conditions)) $cond[] = implode(" and ", $conditions);
			else $cond[] = $conditions;
		}
		$tmp_where_cond = implode(" and ", $cond);
		$sql = "delete from ".$this->getTable()." where ".$tmp_where_cond;
		$r_deleted = $g_db->Execute($sql);
		if($r_deleted)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	/**
	 * 代替旧版本的update
	 * 2007-8-28 以this->primaryKey代替旧有的固定 id字段，使得可以自由选择。
	 */
	function save($posts, $action=null, $id=null, $tbname = null, $conditions = null)
	{
		global $g_db;
		global $primary_id;
		$keys = array_keys($posts);
		$cols = implode($keys,",");
		$tbname = (is_null($tbname))? $this->getTable():trim($tbname);
		if(!empty($primary_id)){
			$sql = "select $cols from ".$tbname." where ".$this->primaryKey."='".$primary_id."'";
		}elseif(!empty($id)){
			$sql = "select $cols from ".$tbname." where ".$this->primaryKey."='".$id."'";
		}else{
			$sql = "select $cols from ".$tbname." where ".$this->primaryKey."='-1'";
		}
		if (!is_null($conditions)) {
			$sql.= $conditions;
		}
		$rs = $g_db->Execute($sql);
		$record = array();
		foreach ($keys as $colname) {
			$record[$colname] = $posts[$colname];
		}
		if (strtolower($action) == "update" || !empty($primary_id)) {
			$insertsql = $g_db->GetUpdateSQL($rs,$record);
		}else {
			$insertsql = $g_db->GetInsertSQL($rs,$record);
		}
		$result = $g_db->Execute($insertsql);
		if (!$result || empty($result)) {
			return false;
		}else {
			return true;
		}
	}

	/**
	 * 得到某条记录的信息
	 *
	 * @param unknown_type $id
	 */
	function read($fields = null, $id = null, $tables = null, $conditions = null)
	{
		global $g_db;
		global $joins;
		$tmp_tablename = null;
		if ($id!==null) {
			$this->id = $id;
		}
		$id = $this->id;
		if (is_array($this->id)) {
			$id = $this->id[0];
		}
		if($tables == null){
			$tmp_tablename = $this->getTable(true);
		}
		if (is_null($fields)) {
			$fields = null;
			$columns = $g_db->MetaColumnNames($this->getTable());
			foreach ($columns as $key=>$val) {
				$fields.=$key." as ".$this->name.uaProcessTableCol($val).",";
			}
			$fields = substr_replace($fields,'',-1,1);
		}
		$sql = null;

		if ($this->id !== null && $this->id !== false) {
			$field = trim($this->name).".".$this->primaryKey;
		}
		$sql = "select ".$fields." from ".$tmp_tablename." where ".$field."='".$id."'";
		if($conditions !=null){
			$sql.= " ".$conditions;
		}
		$res = $g_db->GetRow($sql);
		return $res;
	}

	/**
	 * 得到某个field的值，类似adodb的getone
	 * 2.0用field代替
	 * @param 字段值 $target_val
	 * @param 要得到字段值的字段名称 $get_col
	 * @param 字段名 $target_col
	 * @return unknown
	 */
	function find($target_val,$get_col = "id", $target_col=null)
	{
		global $g_db;
		if(is_null($target_col)) $target_col = $this->primaryKey;
		$sql = "select ".$get_col." from ".$this->getTable(true)." where ".$target_col."='".$target_val."'";
		$res  = $g_db->GetOne($sql);
		return $res;
	}

	/**
	 * 根据条件，得到某一个字段的名称
	 * 代替1.0的find函数
	 * @param 字段名称 $name
	 * @param 条件 $conditions
	 * @param 排序 $order
	 * @return 字段值
	 */
	function field($name, $conditions = null, $order = null) {
		global $g_db;
		
		if ($conditions === null) {
			$conditions = array($this->name . '.' . $this->primaryKey => $this->id);
		}
		if (is_array($conditions)) {
			$tmp_conditions = implode(" and ",$conditions);
			$conditions = $tmp_conditions;
		}
		$sql = "select ".trim($name)." from ".$this->getTable(true)." where ".$conditions;
		$result  = $g_db->GetOne($sql);
		return $result;
	}

	function getFieldAliasNames()
	{
		global $g_db;
		$table_name = $this->getTable();
		$fields = null;
		$columns = $g_db->MetaColumnNames($table_name);
		foreach ($columns as $key=>$val) {
			$fields.=$this->name.".".$key." as ".$this->name.uaProcessTableCol($val).",";
		}
		$fields = substr_replace($fields,'',-1,1);
		return $fields;
	}

	/**
	 * 代替1.0beta的getTableName();
	 *
	 * @param 是否同时取得别名 $alias
	 * @return 数据表（别）名
	 */
	function getTable($alias = false)
	{
		global $tb_prefix;
		$table = $tb_prefix.strtolower(get_class($this));
		if($alias) $table.= " as ".$this->name;
		return $table;
	}

	/**
	 * 代替1.0的 getAmount
	 *
	 * @param unknown_type $conditions
	 * @param unknown_type $countfield
	 * @return unknown
	 */
	function findCount($conditions = null, $countfield = null, $tables = null, $ujoins="")
	{
		global $g_db;
		global $joins;
		$tmp_conditions = null;
		$sql = null;
		if(is_null($countfield)) $countfield = $this->primaryKey;
		if (is_null($tables)) {
			$tables = $this->getTable(true);
		}
		if (!empty($joins)) {
			foreach ($joins as $assoc => $data) {
				$tables.=",".$data['fullTableName'];
				$tmp_conditions.= "and ".$this->name.".".$data['foreignKey']."=".$assoc.".id";
			}
		}
		$sql = "select count(".$countfield.") as Amount from ".$tables." ".$ujoins;
		if (!is_null($conditions)) {
			$sql.= " where ".$conditions." ".$tmp_conditions;
		}
		$return = $g_db->GetOne($sql);
		return $return;
	}

	/**
	 * 代替所有的 getRecords,综合left join,belongsto
	 *
	 * @param unknown_type $fields
	 * @param unknown_type $conditions
	 * @param unknown_type $order
	 * @param unknown_type $limit
	 * @param unknown_type $offset
	 * @param unknown_type $recursive
	 * @return unknown
	 */
	function findAll($fields, $conditions = null, $order = null, $limit = null, $offset = null, $recursive = null)
	{
		global $g_db;
		global $joins;
		$join_fields	= null;
		$orders			= null;
		$records		= null;
		$condition	 	= null;
		if (!empty($joins)) {
			foreach ($joins as $assoc => $data) {
				if(isset($data['foreignKey'])) {
					if(isset($data['PrimaryKey'])) $values[] = " left join ".$data['fullTableName']." on ".$assoc.".".$data['PrimaryKey']."=".$this->name.".".$data['foreignKey'];
					else $values[] = " left join ".$data['fullTableName']." on ".$this->name.".".$data['foreignKey']."=".$assoc.".id ";
				}else $values[] = " left join ".$data['fullTableName']." on ".$this->name.".".$data['foreignKey']."=".$assoc.".id ";
				if($data['fields']) $find_fields[] = $data['fields'];
			}
			$join_fields = implode(" ",$values);
		}

		if (is_null($fields)) {
			$find_fields[] = $this->name.".*";
		}else{
			$find_fields[] = $fields;
		}
		$fields = implode(",",$find_fields);
		$sql = "select ".$fields." from ".$this->getTable(true).$join_fields;
		if (!is_null($conditions)) {
			$condition.= " where ".$conditions;
			$sql.= $condition;
		}
		if (!is_null($order)) {
			$orders.= " order by ".$order;
			$sql.= $orders;
		}
		if (!is_null($limit) && !is_null($offset)) {
			$records.= " limit $limit,$offset";
			$sql.=$records;
		}
		$return = $g_db->GetArray($sql);
		return $return;
	}

	function findAllAndTravel($fields, $conditions = null, $order = null, $limit = null, $offset = null, $recursive = null)
	{
		global $g_db;
		global $joins;
		$join_fields	= null;
		$orders			= null;
		$records		= null;
		$condition	 	= null;
		if (!empty($joins)) {
			foreach ($joins as $assoc => $data) {
				if(isset($data['foreignKey'])) {
					if(isset($data['PrimaryKey'])) $values[] = " left join ".$data['fullTableName']." on ".$assoc.".".$data['PrimaryKey']."=".$this->name.".".$data['foreignKey'];
					else $values[] = " left join ".$data['fullTableName']." on ".$this->name.".".$data['foreignKey']."=".$assoc.".product_id ";
				}else $values[] = " left join ".$data['fullTableName']." on ".$this->name.".".$data['foreignKey']."=".$assoc.".product_id ";
				if($data['fields']) $find_fields[] = $data['fields'];
			}
			$join_fields = implode(" ",$values);
		}

		if (is_null($fields)) {
			$find_fields[] = $this->name.".*";
		}else{
			$find_fields[] = $fields;
		}
		$fields = implode(",",$find_fields);
		$sql = "select ".$fields." from ".$this->getTable(true).$join_fields;
		if (!is_null($conditions)) {
			$condition.= " where ".$conditions;
			$sql.= $condition;
		}
		if (!is_null($order)) {
			$orders.= " order by ".$order;
			$sql.= $orders;
		}
		if (!is_null($limit) && !is_null($offset)) {
			$records.= " limit $limit,$offset";
			$sql.=$records;
		}
		$return = $g_db->GetArray($sql);
		return $return;
	}





	function clicked($id, $add = true)
	{
		global $g_db;
		if($add){
			$sql = "update ".$this->getTable()." set clicked=clicked+1 where id=".$id;
		}
		return $g_db->Execute($sql);
	}

	/**
	 * 修改记录的状态
	 *
	 * @param mixed 要修改的编号 $id
	 * @param 修改为状态 $status
	 * @return boolean
	 */
	 function check($id = null, $status = 0)
	{
		if(is_array($id)){
			$checkId = "id in (".implode(",",$id).")";
		}elseif(intval($id)) {
			$checkId = "id=".$id;
		}else{
			return false;
		}
		$sql = "update ".$this->getTable()." set status='".$status."' where ".$checkId;
		$return = $GLOBALS['g_db']->Execute($sql);
		if($return){
			return true;
		}else {
			return false;
		}
	}

	/**
	 * 更新某个字段
	 * @param mixed 字段名称
	 * @param mixed 新值
	 * @return boolean
	 */
	function saveField($name, $value, $id = null, $conditions = null)
	{
		if(is_array($id)){
			$checkId = "id in (".implode(",",$id).")";
		}elseif(is_int($id)) {
			$checkId = "id=".$id;
		}else{
			$checkId = 1;
		}
		if(empty($conditions)) $conditions = 1;
		if($checkId){
			$sql = "update ".$this->getTable()." set $name='".$value."' where ".$checkId." and ".$conditions;
			$return = $GLOBALS['g_db']->Execute($sql);
		}
		return $return;
	}

	/**
	 * 返回某个表中最大的id，可以表示为最后插入的id号
	 *
	 * @return unknown
	 */
	function getMaxId()
	{
		$sql = "select max(id) from ".$this->getTable();
		$max_id = $GLOBALS['g_db']->GetOne($sql);
		return $max_id;
	}

	function unbindModel()
	{
		return false;
	}

	function bindModel()
	{
		return false;
	}
}
?>
